package com.cloudfast.common.encode;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudfast.common.Constant;

/**
 * 加密算法 数据库解密(yml/环境加密),密码密码,登入加密
 *
 * @author liuyw
 * @date 2020年9月25日
 */
public class EncodeUtils {

    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    private static final String SHA1 = "SHA-1";
    private static SecureRandom random = new SecureRandom();

    /**
     * Aes加密
     *
     * @param value
     * @return
     */
    public static String encodeEnvironment(String value) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(Constant.ASE_IV.getBytes(StandardCharsets.US_ASCII));
            cipher.init(Cipher.ENCRYPT_MODE,
                    new SecretKeySpec(Constant.ASE_KEY.getBytes(StandardCharsets.US_ASCII), "AES"), iv);
            byte[] encryptBytes = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8));
            return Constant.ASE_ENVIRONMENT_PREFIX
                    + new String(Base64.encodeBase64(encryptBytes), StandardCharsets.US_ASCII)
                    + Constant.ASE_ENVIRONMENT_SUFFIX;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 密码加密
     *
     * @param rawPassword
     * @return
     */
    public static String encode(String rawPassword) {
        byte[] salt = EncodeUtils.generateSalt(8);
        byte[] hashPassword = EncodeUtils.sha1(rawPassword.getBytes(), salt, 1024);
        return EncodeUtils.encodeHex(salt) + EncodeUtils.encodeHex(hashPassword);
    }

    /**
     * Hex编码.
     */
    private static String encodeHex(byte[] input) {
        return Hex.encodeHexString(input);
    }

    private static byte[] sha1(byte[] input, byte[] salt, int iterations) {
        return digest(input, SHA1, salt, iterations);
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            if (salt != null) {
                digest.update(salt);
            }
            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 生成随机的Byte[]作为salt.
     *
     * @param numBytes byte数组的大小
     */
    private static byte[] generateSalt(int numBytes) {
        Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }
}
